package com.cy.app.test;

import android.content.Context;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.CancellationSignal;
import android.os.ParcelFileDescriptor;
import android.print.PageRange;
import android.print.PrintAttributes;
import android.print.PrintDocumentAdapter;
import android.print.PrintDocumentInfo;
import android.print.PrintManager;
import android.util.Log;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class PdfPrintUtil {

    private static final String TAG = "PdfPrintUtil";

    /**
     * 开始打印PDF文件的方法
     *
     * @param context 上下文对象
     * @param pdfUri  PDF文件的Uri，用于定位文件在设备中的位置
     */
    public static void printPdf(Context context, Uri pdfUri) {
        PrintManager printManager = (PrintManager) context.getSystemService(Context.PRINT_SERVICE);
        String jobName = "PDF Print Job";
        printManager.print(jobName, new PdfPrintDocumentAdapter(context, pdfUri), new PrintAttributes.Builder().build());
    }

    /**
     * 自定义的打印文档适配器，用于处理PDF文件的打印相关逻辑
     */
    private static class PdfPrintDocumentAdapter extends PrintDocumentAdapter {

        private Context mContext;
        private Uri mPdfUri;

        public PdfPrintDocumentAdapter(Context context, Uri pdfUri) {
            mContext = context;
            mPdfUri = pdfUri;
        }

        @Override
        public void onLayout(PrintAttributes oldAttributes, PrintAttributes newAttributes, CancellationSignal cancellationSignal,
                             LayoutResultCallback callback, Bundle extras) {
            if (cancellationSignal.isCanceled()) {
                callback.onLayoutCancelled();
                return;
            }

            PrintDocumentInfo.Builder builder = new PrintDocumentInfo.Builder("pdf_document")
                  .setContentType(PrintDocumentInfo.CONTENT_TYPE_DOCUMENT)
                  .setPageCount(PrintDocumentInfo.PAGE_COUNT_UNKNOWN);

            PrintDocumentInfo info = builder.build();
            callback.onLayoutFinished(info, true);
        }

        @Override
        public void onWrite(PageRange[] pages, ParcelFileDescriptor destination, CancellationSignal cancellationSignal,
                            WriteResultCallback callback) {
            InputStream input = null;
            OutputStream output = null;
            try {
                input = mContext.getContentResolver().openInputStream(mPdfUri);
                output = new ParcelFileDescriptor.AutoCloseOutputStream(destination);
                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = input.read(buffer)) >= 0 &&!cancellationSignal.isCanceled()) {
                    output.write(buffer, 0, bytesRead);
                }

                if (cancellationSignal.isCanceled()) {
                    callback.onWriteCancelled();
                } else {
                    callback.onWriteFinished(new PageRange[]{PageRange.ALL_PAGES});
                }
            } catch (FileNotFoundException e) {
                Log.e(TAG, "File not found", e);
                callback.onWriteFailed(e.getMessage());
            } catch (IOException e) {
                Log.e(TAG, "IO Exception", e);
                callback.onWriteFailed(e.getMessage());
            } finally {
                try {
                    if (input!= null) {
                        input.close();
                    }
                    if (output!= null) {
                        output.close();
                    }
                } catch (IOException e) {
                    Log.e(TAG, "Error closing streams", e);
                }
            }
        }
    }
}